package com.relax.netty.nio;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Arrays;

/**
 * scattering 和gathering
 * channel不仅仅一次只能读写数据到一个buff,还可以读写一个buffer数组
 */
public class NioTest11 {
    public static void main(String[] args) throws Exception {
        ServerSocketChannel socketChannel = ServerSocketChannel.open();
        InetSocketAddress socketAddress = new InetSocketAddress(8899);
        socketChannel.bind(socketAddress);
        int messageLength = 2 + 3 + 4;
        ByteBuffer[] buffers = new ByteBuffer[3];
        buffers[0] = ByteBuffer.allocate(2);
        buffers[1] = ByteBuffer.allocate(3);
        buffers[2] = ByteBuffer.allocate(4);
        SocketChannel channel = socketChannel.accept();
        while (true) {
            /**
             * 1.把数据读到buffers
             */
            long byteRead = 0;
            while (byteRead < messageLength) {
                long read = channel.read(buffers);
                byteRead += read;
                System.out.println("byteRead:" + byteRead);
                Arrays.asList(buffers).stream().map(buffer -> "position:" + buffer.position() + ",limit:" + buffer.limit())
                        .forEach(System.out::println);
            }

            /**
             * 2.把buffers数据写出去
             */
            //a先反转
            Arrays.asList(buffers).stream().forEach(buff -> buff.flip());
            long bytesWritten = 0;
            while (bytesWritten < messageLength) {
                long r = channel.write(buffers);
                bytesWritten += r;
            }
            //b重置
            Arrays.asList(buffers).stream().forEach(buff -> buff.clear());
            System.out.println("byteRead:" + byteRead + ",bytesWritten:" + bytesWritten);
        }


    }
}
